package a00_LeetCode.LinkedList;

/**
 * @Author quan
 * @Description 链表中倒数第k个节点：给定一个链表: 1->2->3->4->5, 和 k = 2.返回链表 4->5.
 * @Date 2023/3/27 16:19
 */
public class Num22_getKthFromEnd {
    public ListNode getKthFromEnd(ListNode head, int k) {
        int length = getLength(head);
        //边界条件
        if(head == null){
            return null;
        }
        //正常情况
        for (int i = 0; i < length-k; i++) {
            head = head.next;
        }
        return head;
    }
    //传入链表的头部，就可以知道链表的长度
    public int getLength(ListNode head){
        int count = 0;
        while (head!=null){
            head = head.next;
            count++;
        }
        return count;
    }
}
